import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

/**
 * 格式化时间
 */
export function formatTime(time, format = 'YYYY-MM-DD HH:mm:ss') {
  return dayjs(time).format(format)
}

/**
 * 相对时间
 */
export function relativeTimeFormat(time) {
  return dayjs(time).fromNow()
}

/**
 * 高亮搜索关键词
 */
export function highlightKeyword(text, keyword) {
  if (!keyword) return text
  const regex = new RegExp(keyword, 'gi')
  return text.replace(regex, match => `<mark>${match}</mark>`)
}

/**
 * 截取文本
 */
export function truncateText(text, length = 100) {
  if (text.length <= length) return text
  return text.substring(0, length) + '...'
}

/**
 * 去除 HTML 标签
 */
export function stripHtml(html) {
  const div = document.createElement('div')
  div.innerHTML = html
  return div.textContent || div.innerText || ''
}

